<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>upload file</title>
    <style>
        .uploadbox {
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        .uploadbox input {
            margin-top: 10px;
        }
        #img {
            max-width: 400px;
            display: block;
        }
        #drop-box {
            margin: 20px auto;
            width: 600px;
            height: 400px;
            background-color: #f1f1f1;
            border-radius: 10px;
        }
    </style>
</head>
<body>
    <div class="uploadbox">
        <img id="img" src="" alt="">
        <input type="file" id="fileA">
    </div>
    <div id="drop-box">
        <img id="img-a" src="" alt="">
    </div>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <script>
        $(function () {
            $('#fileA').on('change',function (e) {
                const files = e.target.files;
                console.log(files);
                imgToBase64(files, res=> {
                    $('#img').attr('src', res)
                })
            });
            function imgToBase64(files, cb) {
                if(typeof FileReader === 'undefined'){
                    alert('您的浏览器不支持文件上传，请升级您的浏览器');
                    return false;
                }
            //    实例化FileReader对象
                let reader = new FileReader();
            //    读取文件
                reader.readAsDataURL(files[0]);
            //    通过onload 事件拿到文件，并注册一个回调事件，用来上传文件、预览文件等等...
                reader.onload = e=>{
                    cb? cb(e.target.result):null;
                };
            };

            $('#drop-box').on({
                dragenter: dragenter,
                dragover: dragover,
                drop: drop
            });

            function dragenter(e) {
                e.stopPropagation();
                e.preventDefault();
            }

            function dragover(e) {
                e.stopPropagation();
                e.preventDefault();
            }

            function drop(e) {
                e.stopPropagation();
                e.preventDefault();
                const files = e.originalEvent.dataTransfer.files;
                imgToBase64(files, res=>{
                    $('#img-a').attr('src',res);
                })
            }
        })
    </script>
</body>
</html>